package com.dubbo.framework.protocol.http;

import com.alibaba.fastjson.JSONObject;
import com.dubbo.framework.Invocation;
import com.dubbo.framework.register.LocalRegister;
import com.dubbo.framework.register.RemoteMapRegister;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 接受到servlet之后进行处理·
 *
 * @author by Mr. Li 2021/4/28 19:01
 */
@Slf4j
public class HttpServerHandler {
    public void handler(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            log.info("开始处理请求，请求详情：{}", req);
            // 处理请求
            Invocation invocation = JSONObject.parseObject(req.getInputStream(), Invocation.class);

            String interfaceName = invocation.getInterfaceName();

            //// 根据 接口名 去映射表中 获取实现类
            final Class clazz = LocalRegister.getClazz(interfaceName);
            // 改为调用远程服务
//            final Class clazz = RemoteMapRegister.getMetaInfo(interfaceName);
            // 创建实例 调用方法

            final Method method = clazz.getMethod(invocation.getMethodName(), invocation.getParamTypes());
            final String invoke = (String) method.invoke(clazz.newInstance(), invocation.getParams());

            IOUtils.write(invoke, resp.getOutputStream());


        } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }

    }
}
